package com.kpbvip.aikf.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;

@Service
public class OpenRouterService {

    @Value("${openrouter.api.key}")
    private String apiKey;

    @Value("${openrouter.api.url}")
    private String apiUrl;

    @Value("${openrouter.api.module}")
    private String module;


    public OpenAiApi.ChatCompletionRequest parsePromptToChatCompletionMessage2(String prompt,boolean stream) {
        OpenAiApi.ChatCompletionRequest tObj= JSONObject.parseObject(prompt,OpenAiApi.ChatCompletionRequest.class);

        return tObj;
    }


    public OpenAiApi.ChatCompletionRequest parsePromptToChatCompletionMessage(String prompt,boolean stream) {
        try {
            // 解析 JSON 字符串到 ChatCompletionRequest 对象
            JSONObject tObj= JSONObject.parseObject(prompt);
            JSONArray messages =tObj.getJSONArray("messages");
            List<OpenAiApi.ChatCompletionMessage> dList= new ArrayList<>();
            for (int i=0;i<messages.size();i++ ) {
                JSONObject tObj2=messages.getJSONObject(i);
                if (tObj2.getString("role").equals("user")) {
                   Object contentObj= tObj2.get("content");
                    dList.add(new OpenAiApi.ChatCompletionMessage(contentObj, OpenAiApi.ChatCompletionMessage.Role.USER));
                } else if (tObj2.getString("role").equals("assistant")) {
                    dList.add( new OpenAiApi.ChatCompletionMessage(tObj2.getString("content"), OpenAiApi.ChatCompletionMessage.Role.ASSISTANT));

                }else
                if (tObj2.getString("role").equals("system")) {
                    dList.add( new OpenAiApi.ChatCompletionMessage(tObj2.getString("content"), OpenAiApi.ChatCompletionMessage.Role.SYSTEM));
                }else
                if (tObj2.getString("role").equals("tool")) {
                    dList.add( new OpenAiApi.ChatCompletionMessage(tObj2.getString("content"), OpenAiApi.ChatCompletionMessage.Role.TOOL));
                }


            }


            // 创建 OpenAiApi.ChatCompletionRequest 对象并赋值
            OpenAiApi.ChatCompletionRequest request = new OpenAiApi.ChatCompletionRequest(dList, module,tObj.getDouble("temperature"),stream);//tObj.getBoolean("stream")

            return request;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public String getChatCompletion(String prompt) {

        OpenAiApi client = new OpenAiApi(apiUrl, apiKey);


        List<OpenAiApi.ChatCompletionMessage> messages= new ArrayList<>();
        //messages.add(new OpenAiApi.ChatCompletionMessage(prompt, OpenAiApi.ChatCompletionMessage.Role.USER,"xx","",null,"",null));
        //messages.add(parsePromptToChatCompletionMessage(prompt));

        OpenAiApi.ChatCompletionRequest request =parsePromptToChatCompletionMessage(prompt,false);// new OpenAiApi.ChatCompletionRequest(messages, module,1d,false);


        ResponseEntity<OpenAiApi.ChatCompletion> response = client.chatCompletionEntity(request);
        return response.getBody().choices().get(0).message().content();
    }

    public Flux<OpenAiApi.ChatCompletionChunk> getChatCompletionStream(String prompt) {
        OpenAiApi client = new OpenAiApi(apiUrl, apiKey);
      /*  List<OpenAiApi.ChatCompletionMessage> messages= new ArrayList<>();
        messages.add(new OpenAiApi.ChatCompletionMessage(prompt, OpenAiApi.ChatCompletionMessage.Role.USER,"xx","",null,"",null));
        OpenAiApi.ChatCompletionRequest request = new OpenAiApi.ChatCompletionRequest(messages, module,1d,false);*/
        OpenAiApi.ChatCompletionRequest request =parsePromptToChatCompletionMessage(prompt,true);
        Flux<OpenAiApi.ChatCompletionChunk> response = client.chatCompletionStream(request);
        return response;
    }


    public static void main(String[] args) {
        OpenAiApi client = new OpenAiApi("https://api.siliconflow.cn", "sk-naqscsvrltlkmtbirmpuipcjlqcyxcehwrxilyyiafqccjea");

        String prompt="你好,你能做什么",module="Qwen/Qwen2.5-7B-Instruct";
        List<OpenAiApi.ChatCompletionMessage> messages= new ArrayList<>();
        messages.add(new OpenAiApi.ChatCompletionMessage(prompt, OpenAiApi.ChatCompletionMessage.Role.USER,"xx","",null,"",null));
        OpenAiApi.ChatCompletionRequest request = new OpenAiApi.ChatCompletionRequest(messages, module,1d,false);
        ResponseEntity<OpenAiApi.ChatCompletion> response = client.chatCompletionEntity(request);

        String vvv= response.getBody().choices().get(0).message().content();
        System.out.println(vvv);
    }






}